package com.bookstore.framework.security;

import com.bookstore.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Token管理服务
 */
@Component
public class TokenService {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${jwt.expiration:86400}")
    private Long expiration;

    /**
     * Redis中存储Token的前缀
     */
    private static final String TOKEN_PREFIX = "token:";

    /**
     * 创建Token
     * @param userId 用户ID
     * @param username 用户名
     * @param userType 用户类型
     * @return Token
     */
    public String createToken(Long userId, String username, Integer userType) {
        // 生成JWT Token
        String token = jwtTokenUtil.generateToken(userId, username, userType);
        
        // 将Token存入Redis
        String tokenKey = getTokenKey(userId);
        redisUtil.set(tokenKey, token, expiration);
        
        // 存储用户信息
        String userInfoKey = getUserInfoKey(userId);
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("userId", userId);
        userInfo.put("username", username);
        userInfo.put("userType", userType);
        userInfo.put("loginTime", System.currentTimeMillis());
        redisUtil.hmset(userInfoKey, userInfo, expiration);
        
        return token;
    }

    /**
     * 验证Token
     * @param token Token
     * @return 是否有效
     */
    public boolean validateToken(String token) {
        try {
            // 从Token中获取用户ID
            Long userId = jwtTokenUtil.getUserIdFromToken(token);
            if (userId == null) {
                return false;
            }
            
            // 从Redis中获取Token
            String tokenKey = getTokenKey(userId);
            Object cachedToken = redisUtil.get(tokenKey);
            
            // 验证Token是否存在且与Redis中的一致
            return token.equals(cachedToken);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 刷新Token
     * @param token 原Token
     * @return 新Token
     */
    public String refreshToken(String token) {
        try {
            // 从Token中获取用户信息
            Long userId = jwtTokenUtil.getUserIdFromToken(token);
            String username = jwtTokenUtil.getUserNameFromToken(token);
            Integer userType = jwtTokenUtil.getUserTypeFromToken(token);
            
            // 验证原Token
            if (!validateToken(token)) {
                return null;
            }
            
            // 创建新Token
            return createToken(userId, username, userType);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 删除Token
     * @param userId 用户ID
     */
    public void removeToken(Long userId) {
        String tokenKey = getTokenKey(userId);
        String userInfoKey = getUserInfoKey(userId);
        redisUtil.del(tokenKey, userInfoKey);
    }

    /**
     * 获取Token的Redis键
     * @param userId 用户ID
     * @return Redis键
     */
    private String getTokenKey(Long userId) {
        return TOKEN_PREFIX + userId;
    }

    /**
     * 获取用户信息的Redis键
     * @param userId 用户ID
     * @return Redis键
     */
    private String getUserInfoKey(Long userId) {
        return TOKEN_PREFIX + "info:" + userId;
    }
}